package com.shenda.device.analysis;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;

import com.swak.utils.IOUtils;

/**
 * 多文件访问
 * 
 * @author lifeng
 * @date 2020年6月6日 下午10:08:59
 */
public class MultiRandomAccessFile implements Closeable {

	/**
	 * 多个文件
	 */
	private final List<File> files;

	/**
	 * 下一个文件索引
	 */
	private int index;

	/**
	 * 指向其中一个文件
	 */
	private RandomAccessFile csvVisit = null;

	/**
	 * 创建文件访问器 - 按照顺序读取文件
	 * 
	 * @param files
	 * @throws FileNotFoundException
	 */
	public MultiRandomAccessFile(List<File> files, int index) throws FileNotFoundException {
		this.files = files;
		this.index = index;
		this.csvVisit = new RandomAccessFile(this.files.get(this.index++), "r");
	}

	/**
	 * 定位到某个位置
	 * 
	 * @param position
	 * @throws IOException
	 */
	public void seek(long position) throws IOException {
		csvVisit.seek(position);
	}

	/**
	 * 读取文件
	 * 
	 * @return
	 * @throws IOException
	 */
	public String readLine() throws IOException {
		String line = this.csvVisit.readLine();
		while (line == null && this.index < this.files.size()) {
			IOUtils.closeQuietly(this.csvVisit);
			this.csvVisit = new RandomAccessFile(this.files.get(this.index++), "r");
			line = this.csvVisit.readLine();
		}
		return line;
	}

	/**
	 * 放回文件当前的指针
	 * 
	 * @return
	 * @throws IOException
	 */
	public long getFilePointer() throws IOException {
		return csvVisit.getFilePointer();
	}

	/**
	 * 当前文件
	 * 
	 * @return
	 * @throws IOException
	 */
	public int getFileIndex() throws IOException {
		return this.index - 1;
	}

	@Override
	public void close() throws IOException {
		if (csvVisit != null) {
			csvVisit.close();
		}
	}
}